package com.snail.controller;


import com.snail.utils.AudioProcessingUtil;
import com.snail.config.SrtGenerator;
import com.snail.utils.Subtitle;
import com.snail.utils.TranscriptionServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.*;

@RestController
@RequestMapping("/transcription")
public class TranscriptionController {

    @Autowired
    private AudioProcessingUtil audioProcessingUtil;

    @Autowired
    private TranscriptionServiceUtil transcriptionServiceUtil;

    @Autowired
    private SrtGenerator srtGenerator;

    @GetMapping("/process")
    public String transcribeAudio() throws Exception {
        // 1. 指定本地音频文件路径
        String localFilePath = "C:\\Users\\21116\\Downloads\\ww.wav";
        File sourceFile = new File(localFilePath);

        if (!sourceFile.exists()) {
            throw new IOException("音频文件不存在: " + localFilePath);
        }

        // 2. 创建临时工作副本（避免修改原始文件）
        Path tempPath = Files.createTempFile("audio-", ".wav");
        File tempFile = tempPath.toFile();
        Files.copy(sourceFile.toPath(), tempPath, StandardCopyOption.REPLACE_EXISTING);

        try {
            // 3. 获取音频总时长（毫秒）
            long duration = audioProcessingUtil.getAudioDuration(tempFile);
            System.out.println("音频总时长: " + duration + "ms");

            // 4. 计算分段参数（每15秒一段）
            final int segmentDurationSeconds = 30;
            final long segmentDurationMillis = segmentDurationSeconds * 1000L;
            int numSegments = (int) Math.ceil((double) duration / segmentDurationMillis);
            System.out.println("需要分割成 " + numSegments + " 个片段");

            // 5. 创建线程池（优化线程数量）
            int threadCount = Math.min(numSegments, Runtime.getRuntime().availableProcessors());
            ExecutorService executor = Executors.newFixedThreadPool(threadCount);
            List<Future<Subtitle>> futures = new ArrayList<>();

            // 6. 并行处理每个音频片段
            for (int i = 0; i < numSegments; i++) {
                final int segmentIndex = i;
                futures.add(executor.submit(() -> {
                    long startTime = segmentIndex * segmentDurationMillis;
                    long endTime = Math.min(startTime + segmentDurationMillis, duration);

                    System.out.printf("处理片段 %d: %dms - %dms%n",
                            segmentIndex, startTime, endTime);

                    // 分割音频片段
                    File segmentFile = audioProcessingUtil.splitAudio(
                            tempFile, startTime, endTime);

                    try {
                        // 语音识别
                        String text = transcriptionServiceUtil.transcribeAudioFile(segmentFile);
                        return new Subtitle(startTime, endTime, text);
                    } finally {
                        // 确保删除临时片段文件
                        if (!segmentFile.delete()) {
                            System.err.println("警告: 无法删除临时文件: " + segmentFile.getPath());
                        }
                    }
                }));
            }

            // 7. 收集并排序识别结果
            List<Subtitle> subtitles = new ArrayList<>();
            for (Future<Subtitle> future : futures) {
                subtitles.add(future.get());
            }
            subtitles.sort(Comparator.comparingLong(Subtitle::getStartTimeMillis));

            // 8. 关闭线程池
            executor.shutdown();
            if (!executor.awaitTermination(2, TimeUnit.MINUTES)) {
                executor.shutdownNow();
            }

            // 9. 生成SRT字幕
            return srtGenerator.generateSRT(subtitles);

        } finally {
            // 10. 清理临时文件
            if (tempFile.exists() && !tempFile.delete()) {
                System.err.println("警告: 无法删除主临时文件: " + tempFile.getPath());
            }
        }
    }
}